/**
 * Copyright (C) 2011 Andrew C. Love (DNC) <dnc.app.sup@gmail.com>
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.dnc.cloak.framework.security;

import java.io.ByteArrayInputStream;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;

import org.apache.log4j.Logger;

public class X509Loader {
    private static final Logger logger = Logger.getLogger(X509Loader.class.getName());

    private X509Certificate cert = null;
    private static final String X509 = "X.509";

    public X509Loader() {
    }

    public X509Loader(byte[] buffer) {
        load(buffer);
    }

    private synchronized void load(byte[] buffer) {
        try {
            // Read the certificate
            CertificateFactory cf = CertificateFactory.getInstance(X509);
            ByteArrayInputStream bais = new ByteArrayInputStream(buffer);
            while (bais.available() > 0) {
                cert = (X509Certificate) cf.generateCertificate(bais);
                logger.debug(cert.toString());
            }
        }
        catch (Exception e) {
            logger.error("Could not read X.509 certificate", e);
        }
    }

    public static synchronized X509Certificate getCertificate(byte[] buffer) {
        X509Certificate certificate = null;
        try {
            // Read the certificate
            CertificateFactory cf = CertificateFactory.getInstance(X509);
            ByteArrayInputStream bais = new ByteArrayInputStream(buffer);
            while (bais.available() > 0) {
                certificate = (X509Certificate) cf.generateCertificate(bais);
            }
        }
        catch (Exception e) {
            logger.error("Could not load X.509 certificate", e);
        }
        return certificate;
    }

    public X509Certificate getCert() {
        return cert;
    }

    public void setCert(X509Certificate cert) {
        this.cert = cert;
    }   

}
